<template>
  <canvas :id="canvasId" :style="style"></canvas>
</template>

<script>
export default {
  name: "DrawRectImage",
  props: {
    faceImage: {
      type: String,
      default: null
    },
    results: {
      type: Array,
      default: null
    },
    fontSize: {
      type: Number,
      default: 16
    },
  },
  data () {
    return {
      canvasId: 'canvas_' + Math.floor(Math.random()*1000000),
      style: null,
      ctx: null,
    }
  },
  methods: {
    drawText(text, x, y, fontColor = "red", fontSize = this.fontSize) {
      const ctx = this.ctx;
      const oldFont = ctx.font;
      const oldStyle = ctx.fillStyle;
      ctx.font = 'bold ' + fontSize + 'px Arial';
      ctx.fillStyle = fontColor;
      const rect = ctx.measureText(text);
      ctx.fillText(text, x, y);
      ctx.font = oldFont;
      ctx.fillStyle = oldStyle;
      return {x: x + rect.width, y: y + rect.height};
    }
  },
  mounted () {
    let canvas = document.getElementById(this.canvasId)
    let ctx = canvas.getContext('2d')
    this.ctx = ctx;
    let image = new Image()
    image.onload = () => {
      canvas.height = image.height
      canvas.width = image.width
      this.style = {width: image.width + 'px', height: image.height + 'px'}
      ctx.drawImage(image, 0, 0, image.width, image.height)
      ctx.beginPath();
      this.results.forEach((result, idx) => {
        ctx.lineWidth="2"
        ctx.strokeStyle="red"
        ctx.font = 'bold ' + this.fontSize + 'px Arial';
        ctx.fillStyle = "red"
        const { x, y, w, h } = result.location;
        ctx.rect(x, y, w, h)
        const title = `${idx}`;
        const textLoc = this.drawText(title, x, y - 3, "green", 24);
        if (result.match.length > 0) {
          let startX = x
          let startY = y + this.fontSize
          result.match.forEach((match) => {
            const faceTag = match.sampleData[0].value;
            const text = `${match.confidence}% ${faceTag}`;
            let rect = ctx.measureText(text);
            if (startX + rect.width >= x + w) {
              startX = x
              startY += this.fontSize
            }
            ctx.fillText(text, startX, startY)
            startX +=  rect.width + 5
          });
        }
      });

      ctx.stroke()
    }
    image.src = this.faceImage
  }
}
</script>

<style scoped>

</style>
